package com.xigua._栈;

import java.util.Stack;

/**
 * @author LiRongHua
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @date 2022/3/222:21
 */
public class _剑指Offer_30包含min函数的栈 {

    public static void main(String[] args) {
        MinStack minStack = new MinStack();
        minStack.push(-2);
        minStack.push(0);
        minStack.push(-3);
        System.out.println(minStack.min());
        minStack.pop();
        System.out.println(minStack.top());
        System.out.println(minStack.min());
    }

}

class MinStack {

    private  Stack<Integer> stack;
    private  Stack<Integer> min;  //保存当前栈最小元素

    public MinStack() {
        stack = new Stack<Integer>();
        min = new Stack<Integer>();
    }

    public void push(int x) {
        stack.push(x);
        //如果当前min为空或者min的栈顶元素小于当前插入x的值,则也将该元素插入到min栈中
       if (min.isEmpty() || x < min.peek() ) min.push(x);
    }

    public void pop() {
        Integer pop = stack.pop();
        if (pop.equals(min.peek())) min.pop();
    }

    public int top() {
        return stack.peek();
    }

    public int min() {
        return min.peek();
    }
}
